package mj.scott.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;

@Component
public class OSSUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传字节数组到OSS，返回文件URL
     * @param bytes 图片字节数组
     * @param fileName 文件名（如：qrcode/table1.png）
     * @return 图片URL
     */
    public String upload(byte[] bytes, String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 上传文件
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(bytes));
            // 返回URL（格式：https://bucketName.endpoint/fileName）
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 删除OSS上的文件
     * @param fileName 文件名
     */
    public void deleteFile(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucketName, fileName);
        } finally {
            ossClient.shutdown();
        }
    }
}